<template>
  <div class="store-appointments">
    <div class="page-header">
      <h2>我的预约管理</h2>
      <p>管理您店铺的所有预约记录</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.total }}</div>
              <div class="stat-label">总预约数</div>
            </div>
            <el-icon class="stat-icon"><Calendar /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card pending">
            <div class="stat-content">
              <div class="stat-number">{{ stats.pending }}</div>
              <div class="stat-label">待确认</div>
            </div>
            <el-icon class="stat-icon"><Clock /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card confirmed">
            <div class="stat-content">
              <div class="stat-number">{{ stats.confirmed }}</div>
              <div class="stat-label">已确认</div>
            </div>
            <el-icon class="stat-icon"><Check /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card completed">
            <div class="stat-content">
              <div class="stat-number">{{ stats.completed }}</div>
              <div class="stat-label">已完成</div>
            </div>
            <el-icon class="stat-icon"><CircleCheck /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select 
            v-model="filterForm.status" 
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="待确认" :value="0" />
            <el-option label="已确认" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型">
          <el-input 
            v-model="filterForm.serviceType" 
            placeholder="请输入服务类型"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadAppointments">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预约列表 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>预约列表</span>
          <div class="header-actions">
            <el-button 
              type="primary" 
              @click="loadAppointments"
              :loading="loading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="appointments" 
        v-loading="loading"
        stripe
        style="width: 100%"
        @row-click="viewAppointmentDetail"
      >
        <el-table-column prop="id" label="预约ID" width="80" />
        <el-table-column prop="username" label="客户姓名" width="120" />
        <el-table-column prop="appointmentDate" label="预约日期" width="120" />
        <el-table-column prop="appointmentHour" label="预约时间" width="100">
          <template #default="{ row }">
            {{ row.appointmentHour }}:00-{{ row.appointmentHour + 1 }}:00
          </template>
        </el-table-column>
        <el-table-column prop="packageName" label="服务类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="预约时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 0"
              type="success" 
              size="small"
              @click.stop="confirmAppointment(row)"
            >
              确认
            </el-button>
            <el-button 
              v-if="row.status === 1"
              type="primary" 
              size="small"
              @click.stop="completeAppointment(row)"
            >
              完成
            </el-button>
            <el-button 
              v-if="row.status < 2"
              type="danger" 
              size="small"
              @click.stop="cancelAppointment(row)"
            >
              取消
            </el-button>
            <el-button 
              type="info" 
              size="small"
              @click.stop="viewAppointmentDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预约详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="预约详情" 
      width="600px"
    >
      <div v-if="selectedAppointment" class="appointment-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约ID">
            {{ selectedAppointment.id }}
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">
            {{ selectedAppointment.username }}
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">
            {{ selectedAppointment.appointmentDate }}
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ selectedAppointment.appointmentHour }}:00-{{ selectedAppointment.appointmentHour + 1 }}:00
          </el-descriptions-item>
          <el-descriptions-item label="服务类型">
            {{ selectedAppointment.packageName }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedAppointment.status)">
              {{ getStatusText(selectedAppointment.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ formatDateTime(selectedAppointment.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" v-if="selectedAppointment.updateTime">
            {{ formatDateTime(selectedAppointment.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedAppointment.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedAppointment && selectedAppointment.status === 0"
            type="success"
            @click="confirmAppointment(selectedAppointment)"
          >
            确认预约
          </el-button>
          <el-button 
            v-if="selectedAppointment && selectedAppointment.status === 1"
            type="primary"
            @click="completeAppointment(selectedAppointment)"
          >
            完成预约
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Calendar, Clock, Check, CircleCheck, Search, Refresh 
} from '@element-plus/icons-vue'
import { 
  getStoreManagerAppointments,
  confirmAppointment as confirmAppointmentApi,
  completeAppointment as completeAppointmentApi,
  cancelAppointment as cancelAppointmentApi
} from '@/api/appointment'

// 响应式数据
const loading = ref(false)
const appointments = ref([])
const detailDialogVisible = ref(false)
const selectedAppointment = ref(null)

// 筛选表单
const filterForm = reactive({
  dateRange: null,
  status: null,
  serviceType: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 统计数据
const stats = computed(() => {
  const total = appointments.value.length
  const pending = appointments.value.filter(item => item.status === 0).length
  const confirmed = appointments.value.filter(item => item.status === 1).length
  const completed = appointments.value.filter(item => item.status === 2).length
  
  return { total, pending, confirmed, completed }
})

// 页面加载时获取数据
onMounted(() => {
  loadAppointments()
})

// 加载预约数据
const loadAppointments = async () => {
  loading.value = true
  try {
    // 构建搜索参数
    const params = {}

    // 处理日期范围
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }

    // 处理状态
    if (filterForm.status !== null && filterForm.status !== undefined) {
      params.status = filterForm.status
    }

    // 处理服务类型
    if (filterForm.serviceType && filterForm.serviceType.trim()) {
      params.serviceType = filterForm.serviceType.trim()
    }

    const response = await getStoreManagerAppointments(params)
    if (response.code === 200) {
      appointments.value = response.data || []
      pagination.total = appointments.value.length
    } else {
      ElMessage.error(response.message || '获取预约数据失败')
    }
  } catch (error) {
    console.error('获取预约数据失败:', error)
    ElMessage.error('获取预约数据失败')
  } finally {
    loading.value = false
  }
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    dateRange: null,
    status: null,
    serviceType: ''
  })
  pagination.page = 1
  loadAppointments()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
}

// 确认预约
const confirmAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认预约 ${appointment.id} 吗？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await confirmAppointmentApi(appointment.id)
    if (response.code === 200) {
      ElMessage.success('预约确认成功')
      loadAppointments()
      detailDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '预约确认失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认预约失败:', error)
      ElMessage.error('确认预约失败')
    }
  }
}

// 完成预约
const completeAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要完成预约 ${appointment.id} 吗？`,
      '完成预约',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await completeAppointmentApi(appointment.id)
    if (response.code === 200) {
      ElMessage.success('预约完成成功')
      loadAppointments()
      detailDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '预约完成失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成预约失败:', error)
      ElMessage.error('完成预约失败')
    }
  }
}

// 取消预约
const cancelAppointment = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消预约 ${appointment.id} 吗？`,
      '取消预约',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await cancelAppointmentApi(appointment.id)
    if (response.code === 200) {
      ElMessage.success('预约取消成功')
      loadAppointments()
      detailDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '预约取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败')
    }
  }
}

// 查看预约详情
const viewAppointmentDetail = (appointment) => {
  selectedAppointment.value = appointment
  detailDialogVisible.value = true
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 待确认
    1: 'primary',  // 已确认
    2: 'success',  // 已完成
    3: 'danger'    // 已取消
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待确认',
    1: '已确认',
    2: '已完成',
    3: '已取消'
  }
  return statusMap[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.store-appointments {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card.pending {
  border-left: 4px solid #e6a23c;
}

.stat-card.confirmed {
  border-left: 4px solid #409eff;
}

.stat-card.completed {
  border-left: 4px solid #67c23a;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32px;
  color: #dcdfe6;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.appointment-detail {
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
